package com.george.reversing;

import java.io.IOException;

import com.george.reversing.util.Camera2Proxy;

import android.app.Service;
import android.content.Context;
import android.hardware.Camera;
import android.media.Image;
import android.media.ImageReader;
import android.util.Log;
import android.util.Size;
import android.graphics.SurfaceTexture;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

public class MyWindow extends LinearLayout implements SurfaceTextureListener {

	   private Camera2View mCameraView;

	    private Camera2Proxy mCameraProxy;
	    private static final String TAG = "MyWindow";

	/**
	 * 相机类
	 */
	private Context context;

	private WindowManager mWindowManager;

	public MyWindow(Context context) {
		super(context);
		LayoutInflater.from(context).inflate(R.layout.fragment_camera, this);
		this.context = context;
		
		initView();
	}

	private void initView() {

		  mCameraView = (Camera2View) findViewById(R.id.camera_view);
	        mCameraProxy = mCameraView.getCameraProxy();
	        mCameraView.setSurfaceTextureListener(this);
	        mCameraProxy.setImageAvailableListener(mOnImageAvailableListener);
		mWindowManager = (WindowManager) context.getSystemService(Service.WINDOW_SERVICE);
	}

    private ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
        	Log.e(TAG, "---------------------onImageAvailable");
            Image image = reader.acquireLatestImage();
            if (image == null) {
            	return;
            }
            image.close();
        }
    };
    
	@Override
	public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
		Log.e(TAG, "---------------------onSurfaceTextureAvailable");
		 mCameraProxy.openCamera();
         mCameraProxy.setPreviewSurface(surface);
         // 根据相机预览设置View大小，避免显示变形
         Size previewSize = mCameraProxy.getPreviewSize();
         mCameraView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth());
	}

	@Override
	public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
		Log.e(TAG, "---------------------onSurfaceTextureDestroyed");
		  mCameraProxy.releaseCamera();
		return false;
	}

	@Override
	public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

	}

	@Override
	public void onSurfaceTextureUpdated(SurfaceTexture surface) {

	}

}
